package com.tjbank.cssys.web.config;

import com.tjbank.cssys.web.util.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Properties;

@Component
@Intercepts({@org.apache.ibatis.plugin.Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})
public class MybatisInterceptorConfig implements Interceptor {
    private static Logger logger = LoggerFactory.getLogger(MybatisInterceptorConfig.class);
   @Autowired
   private RedisService redisService;
    /*自定义SQL*/
    private String resetSql(String sql,String userCode) {
        StringBuffer stringBuffer=new StringBuffer(" and t.bank = (select *  from (select g.Name from iam_user u inner join iam_group g on  g.ID=u.ORGAN_ID WHERE u.USER_CODE='");
        stringBuffer.append(userCode).append("'LIMIT 1)h)");
        String resultSql=null;
        if(sql.contains("group by")){
            String []sqlArr= sql.split("group by");
            resultSql=sqlArr[0]+stringBuffer.toString()+" group by "+sqlArr[1];
        }else if(sql.contains("GROUP BY")){
            String []sqlArr= sql.split("GROUP BY");
            resultSql=sqlArr[0]+stringBuffer.toString()+" GROUP BY "+sqlArr[1];
        } else if(sql.contains("order by")){
            String []sqlArr= sql.split("order by");
            resultSql=sqlArr[0]+stringBuffer.toString()+" order by "+sqlArr[1];
        } else {
            resultSql = sql;
        }
        logger.info("------修改后的sql:" + resultSql);

        return resultSql;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        resetSql(invocation);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    private void resetSql(Invocation invocation) {
        Object userCode= redisService.get(Thread.currentThread().getId()+"");
        if(null==userCode|| "".equals(userCode)) return ;
        logger.info("-----mybatis 拦截 ThreadId"+Thread.currentThread().getId());
        final Object[] args = invocation.getArgs();
        BoundSql boundSql = (BoundSql) args[5];
        logger.info("----------++++++sql:"+boundSql.getSql());
        if (StringUtils.isNotEmpty(boundSql.getSql())) {
            modify(boundSql, "sql", resetSql(boundSql.getSql(),userCode.toString()));
        }
    }

    private static void modify(Object object, String fieldName, Object newFieldValue) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            field.set(object, newFieldValue);
        } catch (Exception e) {
            logger.error("mybatis拦截异常",e.getMessage());
        }
    }
}
